package com.yhh.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FieldsFilter {
    public static Map<String, Object> filter(Object object, List<String> fieldNames){
        if(object == null){
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        JSONObject json = JSON.parseObject(JSON.toJSONString(object));
        fieldNames.forEach(name ->{
            Object value = json.get(name);
            map.put(name,value);
        });
        return map;
    }

    public static List<Map<String, Object>> filter(List<Object> list, List<String> fieldNames){
        if(list == null || list.size() == 0){
            return null;
        }
        List<Map<String, Object>> maps = new ArrayList<>();
        list.forEach(obj ->{
            maps.add(filter(obj,fieldNames));
        });
        return maps;
    }
}
